import Axios, { AxiosPromise } from 'axios'
import { Notification, Message, Loading } from 'element-ui'

interface HResponse {
    success: boolean
    message: string
    [key: string]: any
}

// axios请求拦截器
let loading: any;
Axios.interceptors.request.use(config => {
    let token = sessionStorage.getItem('token');
    config.headers['access_token'] = token;
    loading = Loading.service({
        fullscreen: true,
        lock: true
    })
    return config
})

Axios.interceptors.response.use(
    (response: any) => {
        loading.close()
        if (response.status === 200) {
            if (response.data.hasOwnProperty('code') && response.data.code == 200) {
                let data = response.data
                return data
            } else {
                if (response.data.hasOwnProperty('msg')) {
                    Message.error(response.data.msg)
                    return Promise.reject(response.data.msg)
                } else {
                    Message.error(response.data.message)
                    return Promise.reject(response.data.message)
                }
            }
        } else {
            return Promise.reject(response.message)
        }
    },
    error => {
        Notification.error('请求失败')
        if (error.code === 'ECONNABORTED') {
            Notification.error('请求超时')
        }
        loading.close()
        return Promise.reject(error.response.data.message)
    }
)

const http = {
    getRequest: async (url: any, params: any = null) => {
        let apiUrl = process.env.VUE_APP_URL_PREFIX + url
        let config: any = {
            method: 'get',
            url: apiUrl,
            params: params,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            timeout: 30000
        }
        return Axios(config).catch(error => {
            return Promise.reject(error)
        }) as Promise<HResponse>
    },
    postRequest: async (url: any, params: any) => {
        let apiUrl = process.env.VUE_APP_URL_PREFIX + url
        let config: any = {
            method: 'post',
            url: apiUrl,
            data: JSON.stringify(params),
            headers: {
                'Content-Type': 'application/json',
            }
        }
        return Axios(config).catch(error => {
            return Promise.reject(error)
        }) as Promise<HResponse>
    },
    uploadRequest: async (url: any, file: File) => {
        let fileParam = new window.FormData();
        fileParam.append('file', file)
        let config: any = {
            method: 'post',
            url,
            data: fileParam,
            headers: {
                'Content-Type': 'multipart/form-data',
            }
        }
        return Axios(config).catch(error => {
            return Promise.reject(error)
        }) as Promise<HResponse>
    },
}

export default http